<template>
  <section class="component resource-control">
    <data-box :data="dataSet" :maxHeight="500" :selectionList.sync="selectionList" @update:selectionList="onSelectionListChange">
      <template slot="columns">
        <el-table-column prop="name" label="功能名称" :min-width="$helper.getColumnWidth(4)" align="center">
        </el-table-column>
        <el-table-column prop="remark" label="描述" :min-width="$helper.getColumnWidth(3)" align="center">
        </el-table-column>
      </template>
    </data-box>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import DataBox from "~/components/common/data-box.vue";
import { Emit, Watch, Model, Prop } from "vue-property-decorator";
import { State } from "vuex-class"

@Component({
  components: {
    DataBox
  }
})
export default class ResourceControl extends Vue {
  @State private controlResource: any[]

  private controlDataSource: any[] = []
  private dataSet: any[] = []
  private selectionList: any[] = []

  @Prop()
  private currentTreeId: string;

  // 选中的控件资源
  @Prop()
  private controlCheckedIds: any[]

  @Model('selected-change', {
    type: Array,
    default: () => []
  })
  private selectedControlIds: string[]

  @Emit('selected-change')
  private emitSelectedChange(val) { }


  @Emit('check-tree-node')
  private emitCheckTreeNode() { }

  private created() {
    this.controlDataSource = this.controlResource.map(v => ({ ...v })).sort((a, b) => a.sort - b.sort)
  }

  @Watch('currentTreeId', { immediate: true })
  private onCurrentTreeIdChange(val) {
    console.log(this.emitCheckTreeNode(),'val')
    this.dataSet = this.controlDataSource.filter(x => x.parent === val)
    this.selectionList = this.dataSet.filter(x => this.selectedControlIds.includes(x.id))
  }

  private onSelectionListChange(val) {
    if (val.length) this.emitCheckTreeNode()
    const unCheckKeys = this.dataSet.filter(x => val.findIndex(v => v.id === x.id) < 0).map(v => v.id)
    const keySet = new Set(val.map(v => v.id).concat(this.selectedControlIds))
    unCheckKeys.forEach(v => keySet.delete(v))
    console.log(keySet,'keySet')
    this.emitSelectedChange(Array.from(keySet))
  }
}
</script>

<style lang="less">
.component.resource-control {
  .data-box {
    padding: 0;
    .table {
      padding: 0;
    }
  }
}
</style>
